<template>
    <div>
        <v-list-item :active="isSelected" @click="handleClick" :class="{ 'v-list-item--active': isSelected }"
            :style="{ paddingLeft: (level * 20 + 16) + 'px' }">
            <template #prepend v-if="hasChildren">
                <v-btn :icon="isExpanded ? 'mdi-chevron-down' : 'mdi-chevron-right'" variant="text" size="small"
                    @click="handleToggleClick" />
            </template>

            <template #prepend v-else>
                <div style="width: 40px;"></div>
            </template>

            <v-list-item-title>{{ item.menuName }}</v-list-item-title>

            <template #append>
                <v-icon v-if="!item.isLeaf" size="small">
                    mdi-folder
                </v-icon>
                <v-icon v-else size="small">
                    mdi-file-document-outline
                </v-icon>
            </template>
        </v-list-item>

        <!-- 递归渲染子节点 -->
        <template v-if="isExpanded && item.children">
            <MenuListItem v-for="child in item.children" :key="child.id" :item="child" :level="level + 1"
                :selected-id="selectedId" :expanded-nodes="expandedNodes" @select="$emit('select', $event)"
                @toggle="$emit('toggle', $event)" @load-children="$emit('load-children', $event)" />
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

interface MenuNode {
    id: string;
    menuName: string;
    children?: MenuNode[];
    isLeaf?: boolean;
    hasChildren?: boolean;
    [key: string]: any;
}

interface Props {
    item: MenuNode;
    level: number;
    selectedId: string;
    expandedNodes: Set<string>;
}

const props = withDefaults(defineProps<Props>(), {
    level: 0,
    selectedId: '',
});

const emit = defineEmits(['select', 'toggle', 'load-children']);

const isExpanded = computed(() => props.expandedNodes.has(props.item.id));
const hasChildren = computed(() => props.item.hasChildren || (props.item.children && props.item.children.length > 0));
const isSelected = computed(() => props.selectedId === props.item.id);

const handleClick = () => {
    emit('select', props.item);
};

const handleToggleClick = async (e: Event) => {
    e.stopPropagation();

    if (!isExpanded.value && hasChildren.value && (!props.item.children || props.item.children.length === 0)) {
        // 需要加载子节点
        await emit('load-children', props.item.id);
    }

    emit('toggle', props.item.id);
};
</script>

<style scoped>
.v-list-item--active {
    background-color: rgba(25, 118, 210, 0.1) !important;
    color: rgb(25, 118, 210) !important;
}
</style>